package com.example.cas.clienttwo;

import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.util.Map;

/**
 * @program: casdemo
 * @description: 启动页
 * @author: 张 桥
 * @create: 2020-08-17 14:55
 */
@Controller
public class IndexController {

    @RequestMapping("/index")
    public String index(HttpServletRequest request) {

        //获取cas给我们传递回来的对象，这个东西放到了session中
        //session的 key是 _const_cas_assertion_
        Assertion assertion = (Assertion) request.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);

        //获取登录用户名
        String loginName =assertion.getPrincipal().getName();
        System.out.printf("登录用户名:%s\r\n",loginName);

        //获取自定义返回值的数据
        Principal principal  = (AttributePrincipal) request.getUserPrincipal();
        if (request.getUserPrincipal() != null) {

            if (principal instanceof AttributePrincipal) {
                //cas传递过来的数据
                Map<String,Object> result =( (AttributePrincipal)principal).getAttributes();
                for(Map.Entry<String, Object> entry :result.entrySet()) {
                    String key = entry.getKey();
                    Object val = entry.getValue();
                    System.out.printf("%s:%s\r\n",key,val);
                }
            }
        }

        return "index";
    }

    @RequestMapping("/loginOut1")
    public String loginOut(HttpSession session) {
        session.invalidate();
        // http://yellowcong.com:8080/cas-client-maven/user/loginOut/success

        // 这个是直接退出，走的是默认退出方式
        return "redirect:http://172.16.2.106:8900/cas/logout";
    }

    @RequestMapping("/loginOut2")
    public String loginOut2(HttpSession session) {
        session.invalidate();
        // 退出登录后，跳转到退成成功的页面，不走默认页面
        return "redirect:http://172.16.2.106:8900/cas/logout?service=https://www.baidu.com/";
    }

    @RequestMapping("/loginOut/success")
    @ResponseBody
    public String loginOut2() {
        return "main";
    }
}
